package com.clz.appdesign.appdependence.retrofit_kotlin

import android.accounts.NetworkErrorException
import android.content.Context
import android.view.Gravity
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ToastUtils
import com.clz.appdesign.appdependence.retrofit_kotlin.entitiy.BaseEntity
import com.google.gson.JsonSyntaxException
import io.reactivex.Observer
import io.reactivex.disposables.Disposable
import java.net.ConnectException
import java.net.UnknownHostException
import java.util.concurrent.TimeoutException


/**
 *  @author chenliangzhi
 *  @date  2018/8/24
 *  @describe
 */
open abstract class BaseObserver<T> : Observer<BaseEntity<T>> {
    private var mContext: Context? = null

    companion object {
        val SUCCESS_CODE: Int = 200
        val ERROR_CODE: Int = 400
    }

    constructor(context: Context) : this() {

        this.mContext = context
    }

    constructor()

    override fun onSubscribe(d: Disposable) {
        requestStart()
    }

    override fun onNext(t: BaseEntity<T>) {
        requestEnd()
        if (t.status == SUCCESS_CODE) {
            onSucceeded(t.data!!)
        } else if (t.status == ERROR_CODE) {
            onHandlerFailed(t.code, t.message)
        }
    }

    override fun onError(e: Throwable) {
        LogUtils.iTag("retrofit2",e.localizedMessage)
        try {
            if (e is ConnectException
                    || e is TimeoutException
                    || e is NetworkErrorException
                    || e is UnknownHostException) {
                onFailure(e, true)
            } else {
                onFailure(e, false)
            }
        } catch (e1: Exception) {
            e1.printStackTrace()
        }

        if (e is JsonSyntaxException) {
            ToastUtils.showShort("数据异常，请稍后再试")
        } else if (e !is UnknownHostException) {
            ToastUtils.showShort("服务器异常，请稍后再试", Gravity.CENTER)
        } else if (e is NetworkErrorException) {
            ToastUtils.showShort("网络连接不可用，检查你的网络设置")
        }
        requestEnd()
    }

    override fun onComplete() {
        requestEnd()
    }


    /**
     * 返回失败
     *
     * @param e
     * @param isNetWorkError 是否是网络错误
     * @throws Exception
     */
    @Throws(Exception::class)
    open fun onFailure(e: Throwable, isNetWorkError: Boolean) {
        if (isNetWorkError) {
            ToastUtils.showShort("网络连接不可用，检查你的网络设置")
        } else {

        }
    }

    protected abstract fun onSucceeded(t: T)
    open fun onHandlerFailed(code: Int, message: String) {
        ToastUtils.showShort(message)
    }

   open protected fun requestStart() {

    }

   open protected fun requestEnd() {}


}